import React, { Component } from 'react'
import { Link,withRouter } from 'react-router-dom'
import { Menu } from 'antd';
import Icon from '@ant-design/icons';
import { connect } from 'react-redux'

import {createSaveTitleAction} from '../../redux/actions/menu_action'
import menuList from '../../config/menuConfig'

import './leftnav.less'
import login from '../../assets/images/logo.png'

const { SubMenu } = Menu;

@connect(
  state => ({}),
  {saveTitle:createSaveTitleAction}
)
@withRouter
class LeftNav extends Component {

  //根据指定的menu数组生成Menu.Item和SubMenu的数组，方法是map+递归
  showMenuList = (target) => {
    return target.map(item => {
      if (!item.children) {
        return (
          <Menu.Item key={item.key} onClick={() => {this.props.saveTitle(item.title)}}>
            <Link to={item.path}>
              <Icon component={item.icon} />
              <span>{item.title }</span>
            </Link>
          </Menu.Item>
        )
      }
      return (
        <SubMenu key={item.key} icon={<Icon component={item.icon}/>} title={item.title}>
          {this.showMenuList(item.children)}
        </SubMenu>
      )
    })
  }

  render () {
    // console.log(this.props);
    const { pathname } = this.props.location
    return (
      <div className='left-nav'>
        <Link className='left-nav-header' to='/admin/home'>
          <img src={login} alt="logo" />
          <h1>管理系统</h1>
        </Link>
        <Menu
          //defaultSelectedKeys:总是根据第一次指定的key进行选中
          //selectedKeys:总是根据最新指定的key进行选中
          defaultSelectedKeys={[pathname.split('/').reverse()[0]]}//默认选中
          defaultOpenKeys={pathname.split('/').splice(2)}//默认打开
          mode="inline"
          theme="dark"
        >
          {this.showMenuList(menuList)}
          {/* <Menu.Item key="/admin/home">
            <Link to='/admin/home'>
              <HomeOutlined />
              <span>首页</span>
            </Link>
          </Menu.Item>
          <SubMenu key="products" icon={<PicLeftOutlined />} title="商品">
            <Menu.Item key="/admin/category">
              <Link to='/admin/category'>
                <HomeOutlined />
                <span>分类管理</span>
              </Link>
            </Menu.Item>
            <Menu.Item key="/admin/product">
              <Link to='/admin/product'>
                <HomeOutlined />
                <span>商品管理</span>
              </Link>
            </Menu.Item>
          </SubMenu> */}
        </Menu>
      </div>
    )
  }
}

//使用高阶组件withRouter()来包装非路由组件
export default LeftNav


